<?php

// 直接アクセスを拒否する
if (!defined("IN_APP"))
	exit("直接アクセスはできません。");

// ログインしたユーザーのみがアクセスできる
if (!isset($_SESSION['twitter_username']))
	exit("ログインしないとアクセスできません。");

if (@$_POST["action"] == "attendance_check")  {
	$error = false;

	$user_id = $_SESSION['user_id'];
	$group_id = $_SESSION['group'];
	
	$connect = connectToDb();
	
	// リーダーのidを取得する
	$query = sprintf("SELECT owner_id FROM groups WHERE group_id = %s ",
								mysql_real_escape_string($group_id));
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";
		
	$result = mysql_query($query, $connect);
	
	$row = mysql_fetch_assoc($result);

	$group_name = getGroupName($connect, $group_id);

	$params = array();
	
	$params['status'] = "【{$group_name}】【出欠確認】 " . $MESSAGES['TWITTER_ATTENDANCE'];
	$params['trim_user'] = 1;
	
	try {
		$response = $twitter->post_statusesUpdate($params)->response;
		
		if ($response) {
			$createdat = strtotime($response['created_at']);
		
			$date = date("Y-m-d", $createdat);
			$time = date("H:i:s", $createdat);
			
			// データベースを更新する
			$query = "INSERT INTO attendance (group_id, user_id, status, date, time, tweet_id) ";
			$query.= sprintf("VALUES (%s, %s, %s, '%s', '%s', %s)",
								mysql_real_escape_string($group_id),
								mysql_real_escape_string($response['user']['id_str']),
								"1",
								mysql_real_escape_string($date),
								mysql_real_escape_string($time),
								mysql_real_escape_string($response['id_str']));
								
			mysql_query($query, $connect);
		} else {
			$error = "Error";
		}
	}
	catch (Exception $e) {
		$error = $MESSAGES['TWITTER_POST_FAILURE'];
	}
	
	if (!$error) {
		echo "success|" . $MESSAGES['ATTENDANCE_POST_SUCCESSFUL'];
	}
	else {
		echo "error|" . $error;
	}
	
	// MySQLとの接続を切断する
	mysql_close($connect);
}
?>